<?php

namespace Portal\Api;

use Portal\Common\DataApi as Api;
use PhalApi\Exception\BadRequestException;

// use PhalApi\Api;

/**
 *字典类型接口
 * @author chenwengen 20240420
 */
class DictType extends Api
{
    public function getRules()
    {
        return array(
            'tableList' => array(
                 'page' => array('name' => 'pageNum', 'type' => 'int', 'default' => 1, 'min' => 1, 'desc' => '页码'),
                'limit' => array('name' => 'pageSize', 'type' => 'int', 'default' => 10, 'min' => 1, 'max' => 100, 'desc' => '每页记录数'),
                'keywords' => array('name' => 'keywords', 'type' => 'string','require' => false, 'desc' => '关键字(字典类型名称/编码)'),
            ),
            'createData' => array(
               'code' => array('name' => 'code', 'type' => 'string', 'require' => true,'desc' => '类型编码'),
                 'name' => array('name' => 'name', 'type' => 'string', 'require' => true,'desc' => '类型名称'),
                 'remark' => array('name' => 'remark', 'type' => 'string', 'require' => false,'desc' => '备注'),
                 'status' => array('name' => 'status', 'type' => 'enum', 'require' => false,'range' => array('0', '1'),'desc' => '类型状态(1:启用;0:禁用)'),
              ),
            'deleteData' => array(
                'ids' => array('name' => 'id', 'type' => 'array', 'format' => 'explode', 'seperator' => ',', 'require' => true, 'desc' => \PhalApi\T('ids to delete')),
            ),
            'deleteDataIDs' => array(
                'ids' => array('name' => 'ids', 'type' => 'array', 'format' => 'explode', 'seperator' => ',', 'require' => true, 'desc' => \PhalApi\T('ids to delete'))
            ),
            'updateData' => array(
                'id' => array('name' => 'id', 'type' => 'int', 'require' => true, 'min' => 1, 'desc' => 'ID'),
                 'code' => array('name' => 'code', 'type' => 'string', 'require' => true,'desc' => '类型编码'),
                 'name' => array('name' => 'name', 'type' => 'string', 'require' => true,'desc' => '类型名称'),
                 'remark' => array('name' => 'remark', 'type' => 'string', 'require' => false,'desc' => '备注'),
                 'status' => array('name' => 'status', 'type' => 'enum', 'require' => false,'range' => array('0', '1'),'desc' => '类型状态(1:启用;0:禁用)'),
            ),
           'getData' => array(
                'id' => array('name' => 'id', 'type' => 'int', 'require' => true, 'min' => 1, 'desc' => 'ID'),
            ),
        );
    }
    protected function getDataModel()
    {
        return  new \Portal\Model\DictType();
    }

    /**
     * 获取表格列表数据
     * @desc 通用数据接口，获取表格列表数据，默认按ID降序返回，支持分页和搜索
     */
    public function tableList()
    {
        $model = $this->getDataModel();

        $searchParams = array();
        // foreach ($this->searchParams as $key => $val) {
        //     if ($val !==  '') {
        //         $searchParams[$key] = $val;
        //     }
        // }

        // 条件
        $where = !empty($searchParams) ? $searchParams : null;
        $whereParams = array();
        $where = $this->getTableListWhere($where);

        $select = $this->getTableListSelect();
        $order = $this->getTableListOrder();
        $page = $this->page;
        $perpage = $this->limit;

        $total = $model->count($where);
        $items = $total > 0 ? $model->getList($where, $whereParams, $select, $order, $page, $perpage) : array();
        $items = $this->afterTableList($items);

        // return $this->returnDataResult(array('total' => $total, 'items' => $items));
        return $this->returnDataResult(array('total' => $total, 'list' => $items));
    }

    // 列表返回的字段
    protected function getTableListSelect()
    {
        return 'id,name,code,status';
    }

    // 列表的默认排序
    protected function getTableListOrder()
    {
        return 'id DESC';
    }

    // 查询条件
    protected function getTableListWhere($where)
    {
        if ($this->keywords !== null && trim($this->keywords) != '') {
            $where['code LIKE ? OR name LIKE ?'] = array("%$this->keywords%","%$this->keywords%");
        }
        return $where;
    }

    // 取到列表数据后的加工处理
    protected function afterTableList($items)
    {
        return $items;
    }
    /**
      * 创建新数据
      * @desc 通用数据接口，创建一条新数据
      * @return int id 新纪录的ID
      */
    public function createData()
    {
        $model = $this->getDataModel();
        // $newData = $this->newData;
        $array_keys = array_keys($this->getApiRules());
        $newData = [];
        foreach ($array_keys as $key) {
            if ($this->$key !== null) {
                $newData[$key] = $this->$key;
            }
        }
        // 检测必传字段
        foreach ($this->createDataRequireKeys() as $key) {
            if (!isset($newData[$key]) || $newData[$key] === '') {
                throw new BadRequestException(\PhalApi\T('{name} require, but miss', array('name' => $key)));
            }
        }
        // 排除字段
        foreach ($this->createDataExcludeKeys() as $key) {
            unset($newData[$key]);
        }

        // 更多初始化的字段数据
        $newData = $this->beforeCreateData($newData);

        if (empty($newData)) {
            throw new BadRequestException(\PhalApi\T('miss post data'));
        }

        $id = 0;
        try {
            $id = $model->insert($newData);
        } catch (\PDOException $ex) {
            throw new BadRequestException(\PhalApi\DI()->debug ? $ex->getMessage() : \PhalApi\T('system error, please contact engeneer'));
        }

        return $this->returnDataResult(array('id' => intval($id)));
    }

    // 必须提供的字段
    protected function createDataRequireKeys()
    {
        return array('name','code');
    }

    // 不允许客户端写入的字段
    protected function createDataExcludeKeys()
    {
        return array('create_time','update_time');
    }

    // 创建时更多初始化的数据
    protected function beforeCreateData($newData)
    {
        $time = time();
        $newData['create_time'] = $time;
        $newData['update_time'] = $time;
        return $newData;
    }

    /**
     * 根据ID删除数据
     * @desc 根据单个ID删除数据，也可以调整成根据自定义的条件删除数据
     */
    public function deleteData()
    {
        $where = array('id' => $this->ids);
        $model = $this->getDataModel();
        // $rows = !empty($where) ? $model->deleteAll($where) : 0;
        $this->delDict();
        $rows = $model->updateAll(['id' => $this->ids], ['deleted' => 1]) ?: 0;

        return $this->returnDataResult(array('deleted_num' => $rows));
    }

    // 删除数据的条件加工
    protected function getDeleteDataWhere($where)
    {
        return $where;
    }

    /**
     * 批量删除
     * @desc 通用数据接口，根据ID批量删除数据
     */
    public function deleteDataIDs()
    {
        $model = $this->getDataModel();
        $this->delDict();
        $rows = $this->ids ? $model->deleteIds($this->ids) : 0;

        return $this->returnDataResult(array('deleted_num' => $rows));
    }

    private function delDict()
    {
        //删除之前把对应类型字典也删除
        if (is_array($this->ids) && !empty($this->ids)) {
            $codeArr = [];
            $codeDatas = \Portal\Model\DictType::notorm()->select('code')->where(['id' => $this->ids])->fetchAll();
            if (!empty($codeDatas) && is_array($codeDatas)) {
                foreach ($codeDatas as $codeData) {
                    $codeArr[] = $codeData['code'];
                }
            }
        }
        if (isset($codeArr) && !empty($codeArr)) {
            \Portal\Model\Dict::notorm()->where(['type_code' => $codeArr])->delete();
        }
    }
    /**
     * 获取一条数据
     * @desc 通用数据接口，根据ID获取一条数据
     * @return object
     * @exception 403 信息不存在
     */
    public function getData()
    {
        $where = array('id' => $this->id);
        $whereParams = array();
        $select = $this->getDataSelect();

        // 前置条件加工
        $where = $this->getGetDataWhere($where);

        $model = $this->getDataModel();
        $data = $model->getData($where, $whereParams, $select);
        if (!$data) {
            throw new \PhalApi\Exception\BadRequestException("信息不存在", 3);
        }
        $data = $this->afterGetData($data);

        // return $this->returnDataResult(array('data' => $data ? $data : null));
        return $this->returnDataResult($data);
    }

    // 获取单个数据时需要返回的字段
    protected function getDataSelect()
    {
        return 'id,name,code,status,remark';
    }

    // 前置条件加工
    protected function getGetDataWhere($where)
    {
        return $where;
    }

    // 取到数据后的加工处理
    protected function afterGetData($data)
    {
        return $data;
    }

    /**
     * 更新数据
     * @desc 通用数据接口，根据ID更新单条数据
     * @return int|boolean updated_num 更新的数据条数，0表示无更新，1表示更新成功
     */
    public function updateData()
    {
        $model = $this->getDataModel();
        // $updateData = $this->data;
        $array_keys = array_keys($this->getApiRules());
        $updateData = [];
        foreach ($array_keys as $key) {
            if ($this->$key !== null && $key !== 'data') {
                $updateData[$key] = $this->$key;
            }
        }
        unset($updateData['id']);

        foreach ($this->updateDataRequireKeys() as $key) {
            if (!isset($updateData[$key]) || $updateData[$key] === '') {
                throw new BadRequestException(\PhalApi\T('{name} require, but miss', array('name' => $key)));
            }
        }

        foreach ($this->updateDataExcludeKeys() as $key) {
            unset($updateData[$key]);
        }

        if (empty($updateData)) {
            throw new BadRequestException(\PhalApi\T('miss update data'));
        }

        $updateData = $this->beforeUpdateData($updateData);

        try {
            $where = array('id' => $this->id);
            $where = $this->getUpdateDataWhere($where);

            $rows = $model->updateAll($where, $updateData);
            return $this->returnDataResult(array('updated_num' => $rows));
        } catch (\PDOException $ex) {
            throw new BadRequestException(\PhalApi\DI()->debug ? $ex->getMessage() : \PhalApi\T('system error, please contact engeneer'));
        }
    }

    // 更新时必须提供的字段
    protected function updateDataRequireKeys()
    {
        return array();
    }

    // 更新时不允许更新的字段
    protected function updateDataExcludeKeys()
    {
        return array('create_time');
    }

    // 获取更新数据的条件
    protected function getUpdateDataWhere($where)
    {
        return $where;
    }

    // 在更新数据前的处理
    protected function beforeUpdateData($updateData)
    {
        $time = time();
        $updateData['update_time'] = $time;
        return $updateData;
    }
}
